import socketserver
import logging
import json
import threading


class NetData:
    """
    Net传输的JSON对象
    """
    asyn: bool = True
    """
    是否异步模式，异步：发送数据后就不管了，同步：发送数据后还需及时接收到回应的数据
    """
    path: str = ""
    data: object = None

"""
Net传输协议：
顶层： [length:4字节][顶层数据:length字节]
顶层数据：[NetData:json字符串]
"""

class NetHandler(socketserver.BaseRequestHandler):

    # def setup(self, onRecv, send) -> None:
    #     """
    #     一个客户端加入连接时调用
    #     """
    #     logging.info(f"tcp handler setup")
    #     return super().setup(onRecv = onRecv, send = send)

    def handle(self) -> None:
        """
        客户端准备好了后调用
        如果想要持续通信，需要在本方法里面写循环接收，否则本方法执行完后就finish了
        """
        logging.info(f"tcp handler handle")
        super().handle()
        length = int.from_bytes(self.request.recv(4), 'big')
        logging.info(f"length:{length}")
        if not length:
            return
        data = json.loads(self.request.recv(length))
        logging.info(f"recv:{data}")

    def finish(self) -> None:
        """
        客户端关闭连接时调用
        """
        logging.info(f"tcp handle finish")
        return super().finish()

if __name__ == '__main__':
    from py_code.util.logger import defalutLogConfig
    defalutLogConfig()
    logging.debug("start server")
    server = socketserver.ThreadingTCPServer(('127.0.0.1', 9999), NetHandler)
    threading.Thread(target=server.serve_forever, name='server').start()
    while True:
        cmd = input(">>>")
        if cmd.strip() == "exit":
            server.server_close()
            break
    